package com.yhy.common.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 延迟队列默认配置
 * 在我们自定义的交换机中，这是一种新的交换类型，该类型消息支持延迟投递机制 消息传递后并
 * 不会立即投递到目标队列中，而是存储在 mnesia(一个分布式数据系统)表中，当达到投递时间时，才投递到目标队列中。
 * spring.rabbitmq.delay-enable=true 开启
 * *** 全部没有设置的都是没有持久化
 */
@ConditionalOnProperty(name = "spring.rabbitmq.delay-enable", havingValue = "true")
public class DefaultDelayConfig {
    /**
     * 延迟队列
     */
    public static final String DEFAULT_QUEUE = "default.delay.queue";
    /**
     * 延迟routingKey
     */
    public static final String DEFAULT_ROUTING_KEY = "default.delay.routing_key";
    /**
     * 延迟队列交换器
     */
    public static final String DEFAULT_EXCHANGE = "default.delay.exchange";

    /**
     * rabbitmq延时队列插件支持的X_DELAYED_**固定值
     */
    public static final String X_DELAYED_TYPE_KEY = "x-delayed-type";
    public static final String X_DELAYED_TYPE_VALUE = "direct";
    public static final String X_DELAYED_MESSAGE = "x-delayed-message";
    public static final String X_DELAY = "x-delay";

    /**
     * 延迟队列
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.nonDurable(DEFAULT_QUEUE).build();
    }

    /**
     * 延迟队列交换器, x-delayed-type 和 x-delayed-message 固定
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>(16);
        args.put(X_DELAYED_TYPE_KEY, X_DELAYED_TYPE_VALUE);
        return new CustomExchange(DEFAULT_EXCHANGE, X_DELAYED_MESSAGE, false, false, args);
    }

    /**
     * 延迟队列绑定自定义交换器
     *
     * @param delayQueue    队列
     * @param delayExchange 延迟交换器
     */
    @Bean
    public Binding delayBinding(Queue delayQueue, CustomExchange delayExchange) {
        return BindingBuilder.bind(delayQueue).to(delayExchange).with(DEFAULT_ROUTING_KEY).noargs();
    }

}
